package main

import "fmt"

// 观察者接口
type Observer interface {
	Update(news string)
}

// 订阅者（观察者）
type Subscriber struct {
	name string
}

func (s *Subscriber) Update(news string) {
	fmt.Printf("%s received news: %s\n", s.name, news)
}

// 新闻发布者（主题）
type NewsPublisher struct {
	subscribers []Observer
}

// 添加订阅者
func (p *NewsPublisher) Subscribe(observer Observer) {
	p.subscribers = append(p.subscribers, observer)
}

// 移除订阅者
func (p *NewsPublisher) Unsubscribe(observer Observer) {
	for i, sub := range p.subscribers {
		if sub == observer {
			p.subscribers = append(p.subscribers[:i], p.subscribers[i+1:]...)
			break
		}
	}
}

// 发布新闻并通知所有订阅者
func (p *NewsPublisher) PublishNews(news string) {
	fmt.Printf("Publishing news: %s\n", news)
	for _, sub := range p.subscribers {
		sub.Update(news)
	}
}

func main() {
	// 创建新闻发布者
	publisher := &NewsPublisher{}

	// 创建订阅者
	alice := &Subscriber{name: "Alice"}
	bob := &Subscriber{name: "Bob"}

	// 订阅新闻
	publisher.Subscribe(alice)
	publisher.Subscribe(bob)

	// 发布新闻
	publisher.PublishNews("Breaking news: Go 12.9.20 released!")

	// 取消订阅
	publisher.Unsubscribe(bob)

	// 再次发布新闻
	publisher.PublishNews("Update: Go 12.9.20 features announced!")
}
